import time

import requests
import json

from requests import request

from BladeFerm.Lib.Common import logger as mylog


class DingRebot:
    def __init__(self, url=None, proxy_url=None):
        self.url_real = url
        self.proxy_url = proxy_url
        if self.proxy_url is not None:
            self.url = self.proxy_url
        else:
            self.url = self.url_real

    def post(self, message, name_list=[], isAtAll=False,  msgType='text'):
        hearder = {'Content-Type': 'application/json', 'Connection': 'close'}
        if msgType == "markdown":
            data = {
                "msgtype": "markdown",
                "markdown": {
                    "title": "消息通知：",
                    "text": message
                },
                "at": {
                    "atMobiles": name_list,
                    "atUserIds": [],
                    "isAtAll": isAtAll
                },
                "url": self.url_real
            }
        else:
            data = {
                "msgtype": "text",
                "text": {
                    "content": message
                },
                "at": {
                    "atMobiles": name_list,
                    "isAtAll": isAtAll
                },
                "url": self.url_real
            }

        res = ''
        for i in range(3):
            try:
                mylog.info(f'Send info: {message}')
                mylog.info(data)
                res = requests.post(self.url, data=json.dumps(data), headers=hearder)
                mylog.info(f'Send successfully! result:{res.text}')
                res = str(res.text)
                # print(type(res))
                break
            except Exception as e:
                mylog.info(f'{e}')
                mylog.info("Connection refused by the server..")
                time.sleep(5)
                continue
        return res

    def post_form(self, data):
        res2 = requests.post(self.url, files=data)
        return res2


def requestPost(url, data=None, json=None, **kwargs):
    res = request('post', url, data=data, json=json, **kwargs)
    return res


class BasicRequest:
    def __init__(self):
        pass

    def get_method(self, url, params=None, **kwargs):
        mylog.info(f'get url: {url}')
        mylog.debug(f'get params: {params}')
        mylog.debug(f'get kwargs: {kwargs}')
        response = requests.get(url, params=params, **kwargs)
        mylog.info(f'response status: {response.status_code}')
        mylog.debug(f'response text: {response.text}')
        return response

    def post_method(self, url, data=None, json=None, **kwargs):
        mylog.info(f'post url: {url}')
        mylog.debug(f'post data: {data}')
        mylog.debug(f'post json: {json}')
        mylog.debug(f'post kwargs: {kwargs}')
        response = requests.post(url, data=data, json=json, **kwargs)
        mylog.info(f'response status: {response.status_code}')
        mylog.debug(f'response text: {response.json()}')
        return response

    def request_method(self, url, type='get', **kwargs):
        mylog.info(f'request url: {url}')
        mylog.debug(f'request type : {type}')
        mylog.debug(f'request params : {kwargs}')
        response = request(type, url, **kwargs)
        mylog.info(f'response status : {response.status_code}')
        mylog.debug(f'response text : {response.text}')
        return res

    @staticmethod
    def download_file(url, save_path):
        response = requests.get(url, stream=True)
        # 确保请求成功
        if response.status_code == 200:
            with open(save_path, "wb") as file:
                for chunk in response.iter_content(chunk_size=8192):
                    file.write(chunk)
            return True
        else:
            mylog.info(f"请求失败，状态码：{response.status_code}")
            return False


if __name__ == '__main__':
    message = '通知：aaaaaaaa'
    name_list = []  # ['13509840405']
    url_proxy = 'http://127.0.0.1:5009/send_info'
    url_248 = 'https://oapi.dingtalk.com/robot/send?access_token=4675a4912286a6a74112619d7efd0271630dc5ecf5e17bd38a2bc5e94d0c60db'
    url_test = 'https://oapi.dingtalk.com/robot/send?access_token=4675a4912286a6a74112619d7efd0271630dc5ecf5e17bd38a2bc5e94d0c60db'
    res = DingRebot(url_test).post(message, name_list, isAtAll=True)
    print(res)
